package xxh;

import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;

public class BorrowProcess {
    private Connection connection;

    BorrowProcess(JPanel bookPanel) throws SQLException {
        connection = ConnectDB.getConnection();
        if (connection != null) {
            loadBooks(bookPanel);
        } else {
            JOptionPane.showMessageDialog(bookPanel, "数据库连接失败！", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void loadBooks(JPanel bookPanel) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT Bno, Bname, Bauthor, Bnumber FROM books");
        ResultSet rs = preparedStatement.executeQuery();

        while (rs.next()) {
            String bno = rs.getString("Bno");
            String bname = rs.getString("Bname");
            String author = rs.getString("Bauthor");
            int bnumber = rs.getInt("Bnumber");

            BookPanel panel = new BookPanel(bno, bname, author, bnumber);
            bookPanel.add(panel);
        }
        rs.close();
        preparedStatement.close();
    }

    public boolean borrowBook(String userNo, String bookNo) throws SQLException {
        // 检查库存
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT Bnumber FROM books WHERE Bno = ?");
        preparedStatement.setString(1, bookNo);
        ResultSet rs = preparedStatement.executeQuery();
        int count = 0;
        if (rs.next()) {
            count = rs.getInt(1);
        }

        if (count < 1) { // 库存不足
            rs.close();
            preparedStatement.close();
            return false;
        }

        // 借书记录
        preparedStatement = connection.prepareStatement("INSERT INTO lend (Bno, Uno, Lendtime, Backtime) VALUES (?, ?, ?, ?)");
        preparedStatement.setString(1, bookNo);
        preparedStatement.setString(2, userNo);
        preparedStatement.setDate(3, Date.valueOf(java.time.LocalDate.now()));
        preparedStatement.setDate(4, null);
        preparedStatement.executeUpdate();

        // 更新库存
        preparedStatement = connection.prepareStatement("UPDATE books SET Bnumber = Bnumber - 1 WHERE Bno = ?");
        preparedStatement.setString(1, bookNo);
        preparedStatement.executeUpdate();

        return true;
    }
}
